package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.TimeCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 预约信息Service业务层处理
 *
 * @author success
 * @date 2025-01-15
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询取消预约数量
     *
     * @param userId
     * @return
     */
    @Override
    public int getCancelledReservationCount(Long userId) {

        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getUpdateBy, userId)
                .eq(Reservation::getStatus, 2)
                .between(Reservation::getUpdateTime, startTime, endTime);

        return (int) count(queryWrapper);
    }

    /**
     * 查询每个小时段剩余预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<TimeCountVo> countReservationsForTime(Long time) {
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);

        LocalDateTime startTime = localDateTime.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        List<TimeCountVo> timeCountVoList = reservationMapper.countReservationsForTime(startTime, endTime);
        return timeCountVoList;
    }

    /**
     * 插入预约信息
     *
     * @param reservation
     * @return
     */
    @Override
    public int insertReservation(Reservation reservation) {
        Long userId = UserThreadLocal.getUserId();
        reservation.setCreateBy(String.valueOf(userId));
        reservation.setUpdateBy(String.valueOf(userId));
        reservation.setStatus(0);

        try {
            return save(reservation) ? 1 : 0;
        } catch (Exception e) {
            throw new BaseException("预约信息插入失败");
        }
    }

    /**
     * 分页查询预约信息
     *
     * @param
     * @return
     */
    @Override
    public TableDataInfo<Reservation> pageQueryReservation(Integer pageNum, Integer pageSize, Integer status) {
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请先登录");
        }

        Page<Reservation> page = new Page<>(pageNum, pageSize);
        page = page(page, Wrappers.<Reservation>lambdaQuery()
                .eq(Reservation::getCreateBy, userId)
                .eq(ObjectUtil.isNotEmpty(status), Reservation::getStatus, status)
                .orderByDesc(Reservation::getCreateTime));


        TableDataInfo<Reservation> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());

        return tableDataInfo;
    }

    /**
     * 取消预约
     *
     * @param id
     * @return
     */
    @Override
    public int cancelReservation(Long id) {
        Reservation reservation = getById(id);
        if (ObjectUtil.isEmpty(reservation)) {
            throw new BaseException("预约信息不存在");
        }

        reservation.setStatus(2);
        reservation.setUpdateBy(String.valueOf(UserThreadLocal.getUserId()));
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 定时更新过期预约的状态
     */
    @Override
    public void updateReservationStatus() {
        //提前获取到当前时间减30分钟的时间
        List<Reservation> reservations = reservationMapper.selectList(Wrappers.<Reservation>lambdaQuery()
                .lt(Reservation::getTime, LocalDateTime.now().minusMinutes(30))
                .eq(Reservation::getStatus, 0));

        //设置状态为已过期
        reservations.forEach(reservation -> reservation.setStatus(3));

        //批量更新
        updateBatchById(reservations);
    }
}
